package org.c797797ty.railway.manager;

import org.c797797ty.railway.model.User;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
/**
 * @author C797797ty
 * @data 2025/11/4 14:34
 */

/**
 * 用户会话管理器 - 支持多用户同时登录
 */
public class UserSessionManager {
    private static final ConcurrentMap<String, User> activeSessions = new ConcurrentHashMap<>();
    private static final ConcurrentMap<Integer, String> tokenMap = new ConcurrentHashMap<>();
    private static final AtomicInteger tokenCounter = new AtomicInteger(0);

    // 生成唯一令牌
    public static String createSession(User user) {
        String token = generateToken();
        activeSessions.put(token, user);
        tokenMap.put(user.getId(), token);
        return token;
    }

    // 获取用户会话
    public static User getSession(String token) {
        return activeSessions.get(token);
    }

    // 销毁会话
    public static void invalidateSession(String token) {
        User user = activeSessions.remove(token);
        if (user != null) {
            tokenMap.remove(user.getId());
        }
    }

    // 检查用户是否登录
    public static boolean isLoggedIn(int userId) {
        return tokenMap.containsKey(userId);
    }

    // 生成令牌
    private static String generateToken() {
        return "token-" + tokenCounter.incrementAndGet() + "-" + System.currentTimeMillis();
    }
}
